﻿using Microsoft.Xna.Framework;

namespace Phoenix.Xna.Framework.Components.Compositors
{
    public class FramerateCompositor : TextCompositor
    {
        private float _totalTime;
        private float _fps;
        private string _displayText;

        public float FramesPerSecond { get; private set; }
        public bool DisplayInTitleBar { get; set; }

        public FramerateCompositor(string font)
            : base(font)
        {
            DisplayInTitleBar = true;
            Text = "FPS: ";
        }

        public FramerateCompositor(string font, bool displayInTitleBar)
            : base(font)
        {
            DisplayInTitleBar = displayInTitleBar;
            Text = "FPS: ";
        }

        public FramerateCompositor(string id, string font, bool displayInTitleBar)
            : base(id, font)
        {
            DisplayInTitleBar = displayInTitleBar;
            Text = "FPS: ";
        }

        #region TextCompositor Members

        public override void Update(GameTime gameTime)
        {
            if (Enabled)
            {
                _totalTime += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
                _fps++;

                if (_totalTime >= 1000f)
                {
                    _totalTime = 0;
                    FramesPerSecond = _fps;
                    _fps = 0;
                }

                _displayText = string.Format("{0}{1}", Text, FramesPerSecond);

                if (DisplayInTitleBar)
                {
                    Engine.Instance.Window.Title = _displayText;
                }
            }
        }

        public override void Draw(GameTime gameTime)
        {
            if (Visible && !DisplayInTitleBar)
            {
                if (SpriteFont != null && !string.IsNullOrEmpty(_displayText))
                {
                    SpriteBatch.DrawString(SpriteFont, _displayText, Position, Color, Rotation, Origin, Scale, Effect, LayerDepth);
                }
            }
        }

        #endregion
    }
}
